package leetcode_cn;

/**
 * 字符串转整数
 *
 * @author briarbear
 * @blog https://briarbear.github.io
 * @date 2018-09-05 15:58
 */
public class MyAtoi {



    public int solution(String str){
        if (str.isEmpty()) return 0;
        int sign = 1, base = 0, i = 0, n = str.length();
        while (i < n && str.charAt(i) == ' ') ++i;  //跳过开始的空格
        if (i < n && (str.charAt(i) == '+' || str.charAt(i) == '-')) {
            sign = str.charAt(i++) == '+' ? 1 : -1;
        }

        while (i < n && Character.isDigit(str.charAt(i))) {
            if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
                //数值过大
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            base = base * 10 + (str.charAt(i) - '0');
            i++;
        }

        return base * sign;
    }

    public static void main(String[] args) {
//        System.out.println(new MyAtoi().solution("42"));
        System.out.println(new MyAtoi().solution("  -42"));
//        System.out.println(new MyAtoi().solution("4193 with words"));
//        System.out.println(new MyAtoi().solution("-91283472332"));
//        System.out.println(new MyAtoi().solution("2147483648"));
//        System.out.println(new MyAtoi().solution("-   234"));
        System.out.println(new MyAtoi().solution(" "));

    }
}
